package com.cr.admin.es;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class ESSearchTestRun {
    private RestHighLevelClient client;
    public ESSearchTestRun() {
        initClient(); // 在构造函数中初始化客户端
    }

    public void initClient() {
        HttpHost host=new HttpHost("localhost",9200,"http");
        RestClientBuilder builder = RestClient.builder(host);
        client=new RestHighLevelClient(builder);
    }
    public void closeClient() throws IOException {
        if (client != null) {
            client.close();
        }
    }
    @Test
    public void searchByMatch() throws IOException {
        SearchRequest request=new SearchRequest("news");
        SearchSourceBuilder builder=new SearchSourceBuilder();
        //1.查询条件 内容content 对应查询doc字段属性名字  value 查询的分词词项文本
        MatchQueryBuilder query = QueryBuilders
                .matchQuery("content", "车");
        //2.封装 执行请求 打印返回结果
        builder.query(query);
        builder.from(0);
        builder.size(100);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println("总数:"+response.getHits().getTotalHits().value);
        SearchHit[] hits = response.getHits().getHits();
        if (hits!=null&&hits.length>0) {
            for (SearchHit hit : hits) {
                System.out.println(JSON.parseObject(hit.getSourceAsString(),
                        news.class));
            }
        }
    }

}
